<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
abstract class DMBridgeVersion {

	const DMBRIDGE_VERSION_URL = "http://digital.library.unlv.edu/versions/dmbridge.php";

	/**
	 * @return string
	 */
	private static function getVersionFilePathname() {
		return dirname(__FILE__) . "/../VERSION.txt";
	}

	/**
	 * @param string pathname Parse the file at this pathname
	 * @param string version Returned by reference
	 * @param int seq Returned by reference
	 * @return void
	 */
	private static function parseVersionFile($file, &$version, &$seq) {
		if (file_exists($file)) {
			$data = file_get_contents($file);
			$tmp = explode("\n", $data);
			$version = (string) substr($tmp[0], 0, 20);
			$seq = (int) substr($tmp[1], 0, 3);
		}
	}

	/**
	 * @return array Array of integers representing all available versions of
	 * the HTTP API.
	 */
	public static function getHTTPAPIVersions() {
		return array(1);
	}

	/**
	 * @return int The latest available HTTP API version.
	 */
	public static function getLatestHTTPAPIVersion() {
		return max(self::getHTTPAPIVersions());;
	}

	/**
	 * Retrieves the software version from VERSION.txt, which is created
	 * automatically by the packaging tool.
	 *
	 * @return string
	 */
	public static function getDmBridgeVersion() {
		$version = $seq = 0;
		self::parseVersionFile(self::getVersionFilePathname(), $version, $seq);
		return $version;
	}

	/**
	 * Will increment by 1 with each subsequent release.
	 *
	 * @return int
	 * @see getCurrentDmBridgeVersionSequence()
	 */
	public static function getDmBridgeVersionSequence() {
		$version = $seq = 0;
		self::parseVersionFile(self::getVersionFilePathname(), $version, $seq);
		return $seq;
	}

	/**
	 * Used to compare against the current version on the UNLV Libraries
	 * web server, for automatic notification of new versions in the control
	 * panel.
	 *
	 * @param DMHTTPRequest req Disposable DMHTTPRequest, required for
	 * dependency injection
	 * @return int
	 */
	public static function getCurrentDmBridgeVersionSequence(DMHTTPRequest $req) {
		$req->setURI(new DMURI(self::DMBRIDGE_VERSION_URL));
		$client = new DMHTTPClient($req);
		$response = $client->send();
		return (int) substr($response->getRepresentation()->getBody(), 0, 4);
	}

	/**
	 * @param DMHTTPRequest req Disposable DMHTTPRequest, required for
	 * dependency injection
	 * @return Boolean
	 */
	public static function isNewerDmBridgeVersionAvailable(DMHTTPRequest $req) {
		if (file_exists(self::getVersionFilePathname())) {
			return (self::getDmBridgeVersionSequence()
				< self::getCurrentDmBridgeVersionSequence($req));
		}
		return false;
	}

}
